<template>
  <div class="app-container">
    <SearchForm ref="queryFormRef" :model="queryParam" :inline="true" @reset="handleResetQuery" @search="handleQuery"
      size="default">
      <el-form-item prop="keywords" label="关键字">
        <el-input v-model="queryParam.keywords" placeholder="名称或描述关键字" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <template #ext-btn>
        <el-button v-hasPerm="['dict:add']" type="success" @click="handleOpenDialog()"><i-ep-plus />新增</el-button>
        <el-button v-hasPerm="['dict:del']" type="danger" :disabled="selectionIds.length === 0"
          @click="handleDelete()"><i-ep-delete />删除</el-button>
      </template>
    </SearchForm>

    <el-table ref="dictTableRef" v-loading="loading" :data="dictData" highlight-current-row border row-key="dict_id"
      @row-click="handleRowClick" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" prop="name" width="180" />
      <el-table-column label="描述" prop="description" min-width="155" />
      <el-table-column fixed="right" label="操作" align="center" width="80">
        <template #default="scope">
          <el-button v-hasPerm="['dict:edit']" type="primary" size="small" link @click="handleOpenDialog(scope.row)">
            <i-ep-edit />
          </el-button>
          <el-button v-hasPerm="['dict:del']" type="danger" size="small" link @click="handleDelete(scope.row.role_id)">
            <i-ep-delete />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-if="pagination.total > 0" v-model:total="pagination.total" v-model:page="pagination.current" small
      v-model:limit="pagination.size" @pagination="handlePageChange" />

    <!--表单弹窗-->
    <DictForm v-model="formModal.visible" :title="formModal.title" :selected-item="selectedItem" ref="dictFormRef"
      @close="handleDialogClose" @submit="handleDialogSummit" />
  </div>
</template>

<script setup lang="ts">

defineOptions({
  name: "Dict",
  inheritAttrs: false,
})


// 自定义事件
const emit = defineEmits<{
  rowClick: [data: DictVO]
}>()


import DictAPI, { DictVO } from "@/api/dict"

import DictDetailAPI from "@/api/dict-detail"


const queryFormRef = ref(ElForm)
const dictFormRef = ref(ElForm)

const loading = ref(false)

const selectedItem = ref<DictVO>({})

const selectionIds = ref<number[]>([])

const queryParam = reactive({
  keywords: undefined,
  enabled: undefined,
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})

//构建storex的查询条件
const queryConditon = reactive<QueryCondition>({
  paging: {
    current: pagination.current,
    size: pagination.size,
  },
  sorts: [{
    field: "create_time",
    sort_asc: false
  }]
})

// 字典表格数据
const dictData = ref<DictVO[]>()

// 表单弹窗
const formModal = reactive({
  title: "",
  visible: false,
})

const handlePageChange = () => {
  queryConditon.paging = { ...pagination }
  getPage()
}


/** 分页查询 */
const getPage = () => {
  loading.value = true
  DictAPI.getPage(queryConditon).then((res) => {
    const { status, data } = res
    if (status === 200) {
      dictData.value = data.records
      pagination.total = data.total
    }
  }).finally(() => {
    loading.value = false
  })
}

/** 查询 */
const handleQuery = () => {
  queryConditon.and = []
  if (queryParam.keywords) {
    queryConditon.and?.push(
      { field: "name", op: "like", value: `%${queryParam.keywords}%`, or: [{ field: "description", op: "like", value: `%${queryParam.keywords}%` }] }
    )
  }
  queryConditon.paging = {
    current: 1,
    size: pagination.size
  }
  getPage()
}

/** 重置查询 */
const handleResetQuery = () => {
  queryParam.keywords = undefined
  pagination.current = 1
  handleQuery()
}

/** 行复选框选中记录选中ID集合 */
const handleSelectionChange = (selection: any) => {
  selectionIds.value = selection.map((item: any) => item.dict_id)
}

/** 选择行 */
const handleRowClick = (row: DictVO) => {
  selectedItem.value = { ...row }
  emit("rowClick", row)
}



/** 打开字典弹窗 */
const handleOpenDialog = (row?: DictVO) => {
  if (row && row.dict_id) {
    formModal.title = "编辑字典"
  } else {
    selectedItem.value = {}
    formModal.title = "新增字典"
  }
  formModal.visible = true
}
/** 字典弹窗提交 */
const handleDialogSummit = () => {
  formModal.visible = false
  handleQuery()
}

/** 关闭字典弹窗 */
const handleDialogClose = () => {
  formModal.visible = false
}


/** 删除字典 */
const handleDelete = (dictId?: number) => {
  const dictIds = dictId ? [dictId] : selectionIds.value
  if (!dictIds) {
    ElMessage.warning("请勾选删除项")
    return
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true
    const deleteCondition: QueryCondition = {
      "_cond": { and: [{ field: "dict_id", op: "in", value: dictIds }] }
    }
    const res = await DictAPI.deleteBy(deleteCondition)
    if (res.status === 200) {
      await DictDetailAPI.deleteBy(deleteCondition)
      ElMessage.success("删除成功")
      handleQuery()
    }
  })
}

onMounted(() => {
  handleQuery()
})
</script>
